package com.threegroup.web;

import com.threegroup.common.exception.ErrorCode;
import com.threegroup.common.exception.ParamsException;
import com.threegroup.common.exception.TakeOutException;
import com.threegroup.common.utils.Result;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常统一处理
 */
@Component
/**
 * 全局异常处理
 * @author LinkinStar
 */
@ControllerAdvice
public class GlobalExceptionResolver {
    //设置默认全局异常
    Result result = new Result().error(500,"设置默认全局异常");

    @ExceptionHandler(value = ParamsException.class)
    public @ResponseBody
    Result paramsExceptionHandler(ParamsException e) {
        //对捕获的异常进行处理并打印日志等，之后返回json数据，方式与Controller相同
            result.setCode(e.getCode());
            result.setMsg(e.getMsg());
        return result;
    }

    @ExceptionHandler(value = TakeOutException.class)
    public @ResponseBody
    Result paramsExceptionHandler(TakeOutException e) {
        //对捕获的异常进行处理并打印日志等，之后返回json数据，方式与Controller相同
        result.setCode(e.getCode());
        result.setMsg(e.getMsg());
        return result;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException ex){
        Result result = new Result();
        result.error(ErrorCode.DB_RECORD_EXISTS);

        return result;
    }

    //@ExceptionHandler(value = Exception.class)
    //public Result exceptionHandler() {
    //    return result;
    //}
}


